package com.moss.system.service.impl;

import com.moss.common.constant.Constants;
import com.moss.common.domain.LoginUser;
import com.moss.common.exception.ServiceException;
import com.moss.common.util.*;

import com.moss.common.entity.SysUserEntity;
import com.moss.system.mapper.UserMapper;
import com.moss.system.service.UserService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author gxcc3
 * @date: 2024/8/1 23:43
 */
@Service
public class UserServiceImpl implements UserService {

    @Value("${user.md5-salt}")
    private String md5Salt;

    @Resource
    UserMapper userMapper;

    @Resource
    RedisUtil redisUtil;

    @Resource
    RedisCache redisCache;

    @Override
    public SysUserEntity selectUserByName(String username) {
        return userMapper.selectUserByName(username);
    }

    @Override
    public SysUserEntity getUserInfo(String userId) {
        return userMapper.getUserInfo(userId);
    }

    @Override
    public List<SysUserEntity> selectList(SysUserEntity user) {
        return userMapper.selectList(user);
    }

    @Override
    public void changeStatus(SysUserEntity user) {
        if (StringUtils.isNotEmpty(user.getUserId()) && TokenUtil.isAdmin(user.getUserId(), Constants.ADMIN_KEY)){
            throw new ServiceException("不允许操作超级管理员用户");
        }
        userMapper.updateUser(user);
    }


    @Override
    public SysUserEntity selectUserById(String userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    public void saveUser(SysUserEntity user) {
        //用户密码加盐加密
        String password = user.getPassword();
        String md5Salt = IdUtil.randomUUID();
        String md5Password = MD5Util.getMd5(password, md5Salt);
        user.setPassword(md5Password);
        user.setMd5Salt(md5Salt);
        userMapper.insert(user);
    }


    @Override
    public void updateUser(SysUserEntity user) {
        userMapper.updateById(user);
    }

    @Override
    public void deleteUser(String[] userId) {
        userMapper.deleteById(userId);
    }

    @Override
    public void resetPwd(SysUserEntity user) {
        String md5Salt = IdUtil.randomUUID();
        String newPwd = MD5Util.getMd5(user.getPassword(), md5Salt);
        user.setPassword(newPwd);
        user.setMd5Salt(md5Salt);
        userMapper.updateById(user);
    }
}
